<template>
    <div class="search">
        <el-input v-model="searchContent" @keyup.enter="handleToClick">
            <template #prepend>
                <el-select v-model="selectedSearchEngine" >
                    <template #label="{ label, value }">
                        <img :src="getSelectedIcon(value)" alt="">
                        <span class="text-color">{{ label }}</span>
                    </template>
                    <el-option :label="item.label" :value="item.value" v-for="item in searchEngines">
                        <img :src="getIcon(item.url)" alt="" style="width: 20px;vertical-align: middle;">
                        <span style="margin: 10px;vertical-align: middle;">{{ item.label }}</span>
                    </el-option>
                </el-select>
            </template>
            <template #append>
                <el-button icon="Search" @click="handleToClick" style="color: var(--lan-main-font-color)" />
            </template>
        </el-input>
    </div>
</template>

<script setup>

//搜索引擎列表
const searchEngines = ref([
    { label: '百度', value: '1', url: 'https://www.baidu.com/s?ie=UTF-8&wd=' },
    { label: '搜狗', value: '2', url: 'https://www.sogou.com/web?query=' },
])
//选中的搜索引擎
const selectedSearchEngine = ref('1')
//搜索内容
const searchContent = ref('')

//根据选中值获取图标
const getSelectedIcon = () => {
    const engine = searchEngines.value.filter(i => i.value == selectedSearchEngine.value)[0];
    if (engine) {
        return getProtocolAndDomain(engine.url) + '/favicon.ico'
    }
    return ''
}

//根据链接网站图标
const getIcon = (val) => {
    return getProtocolAndDomain(val) + '/favicon.ico'
}

//获取链接协议+域名+端口部分
const getProtocolAndDomain = (url) => {
    try {
        const parsedUrl = new URL(url);
        return `${parsedUrl.protocol}//${parsedUrl.host}`;
    } catch (e) {
        console.error('无效的URL格式');
        return '';
    }
}

// 点击跳转
const handleToClick = () => {
    const engine = searchEngines.value.filter(i => i.value == selectedSearchEngine.value)[0];
    window.open(engine.url + searchContent.value, "_blank")
}

</script>

<style scoped lang="scss">
.search {
}

.text-color{
    color: var(--lan-main-font-color);
}

.el-input{
    height: 50px;

    :deep(.el-input__wrapper) {
        background-color: rgba(245, 247, 250, 0.6);
    }
    
    :deep(.el-input-group__append) {
        background-color: rgba(245, 247, 250, 0.6);
    }
    
    :deep(.el-input-group__prepend) {
        background-color: rgba(245, 247, 250, 0.6);
    }

    :deep(.el-input__inner) {
        color: var(--lan-main-font-color);
    }
}

.el-select{
    width: 120px;
    height: 50px;

    img {
        width: 20px;
        vertical-align: middle;
    }
    span{
        margin: 10px;
        vertical-align: middle;
    }

    :deep(.el-select__wrapper.el-tooltip__trigger.el-tooltip__trigger){
        height: 50px;
    }
}
</style>